const http = require("http");
const { app, sessionMiddleware } = require("./routes");
const socket = require("socket.io");
const server = http.createServer(app);
const io = socket(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"],
  },
});

const users = [];

// 将 session 中间件传递给 Socket.IO
io.engine.use(sessionMiddleware);

io.on("connection", (socket) => {
  console.log("New client connected");
  const sessionID = socket.request.session.id;
  console.log("Session ID:", sessionID);
  socket.on("disconnect", () => {
    socket.broadcast.emit("userout", { id: sessionID });
    const index = users.findIndex((user) => user.id === sessionID);
    if (index !== -1) {
      users.splice(index, 1);
    }
    console.log("Client disconnected");
  });

  // 自定义事件
  socket.on("login", (data) => {
    const item = {
      id: sessionID,
      name: data.name,
      socket: socket,
      avatar: "https://picsum.photos/50/50",
      isGroup: data.isGroup,
    };

    if (data.isGroup) {
      item.list = [];
    }

    if (users.findIndex((user) => user.id === item.id) === -1) {
      users.push(item);
    }
    const { name, id, isGroup, avatar } = item;
    socket.broadcast.emit("userin", { name, id, isGroup, avatar });
  });

  socket.on("users", () => {
    // Broadcast the message to all connected clients
    // io.emit("message", data);
    socket.emit(
      "users",
      users
        .map((user) => {
          const { name, id, isGroup, avatar } = user;
          const item = { name, id, isGroup, avatar };
          if (user.isGroup) {
            item.list = user.list;
          }
          return item;
        })
        .filter((user) => {
          console.log(user.id, sessionID);
          return user.id !== sessionID;
        })
    );
  });

  socket.on("message", (data) => {
    const { id, msg } = data;
    const user = users.find((user) => user.id === id);
    if (user) {
      user.socket.emit("message", { id: sessionID, msg });
    }
  });
});

server.listen(5008, () => {
  console.log("Server is running on port 5008");
});
